package com.kelaite.procurement.service.impl;

import io.jsonwebtoken.lang.Collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.dto.SalesOrderItemsDTO;
import com.kelaite.procurement.entity.TMaterialMasterClient;
import com.kelaite.procurement.entity.TPurchaseOrder;
import com.kelaite.procurement.entity.TPurchaseOrderExecution;
import com.kelaite.procurement.entity.TPurchaseOrderExecutionItems;
import com.kelaite.procurement.entity.TSalesOrder;
import com.kelaite.procurement.entity.TSalesOrderExecution;
import com.kelaite.procurement.entity.TSalesOrderExecutionItems;
import com.kelaite.procurement.entity.TSalesOrderItems;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.entity.TVendor;
import com.kelaite.procurement.repository.PurchaseOrderExecutionItemsRepository;
import com.kelaite.procurement.repository.PurchaseOrderExecutionRepository;
import com.kelaite.procurement.repository.PurchaseOrderItemsRepository;
import com.kelaite.procurement.repository.PurchaseOrderRepository;
import com.kelaite.procurement.repository.SalesOrderExecutionItemsRepository;
import com.kelaite.procurement.repository.SalesOrderExecutionRepository;
import com.kelaite.procurement.repository.SalesOrderItemsRepository;
import com.kelaite.procurement.repository.SalesOrderRepository;
import com.kelaite.procurement.service.SalesOrderItemsService;
import com.kelaite.procurement.utils.CurrentUserUtils;

@Service
@Transactional
public class SalesOrderItemsServiceImpl implements SalesOrderItemsService{
  
	@Autowired
	private PurchaseOrderItemsRepository purchaseOrderItemsRepository;
	
	@Autowired
	private SalesOrderItemsRepository salesOrderItemsRepository; 
	
	@Autowired
	private SalesOrderRepository salesOrderRepository;
	
	@Autowired
	private SalesOrderExecutionRepository salesOrderExecutionRepository;
	
	@Autowired
	private SalesOrderExecutionItemsRepository salesOrderExecutionItemsRepository;
	
	@Autowired
	private PurchaseOrderRepository purchaseOrderRepository;
	
	@Autowired
	private PurchaseOrderExecutionRepository purchaseOrderExecutionRepository;
	
	@Autowired
	private PurchaseOrderExecutionItemsRepository purchaseOrderExecutionItemsRepository;
	
	@PersistenceContext
	private EntityManager em;
	
	@Override
	public TSalesOrderItems save(TSalesOrderItems persistence) {
		return this.salesOrderItemsRepository.save(persistence);
	}

	@Override
	public TSalesOrderItems getObject(Long id) {
		return this.salesOrderItemsRepository.findOne(id);
	}

	@Override
	public List<TSalesOrderItems> getAll() {
		return this.salesOrderItemsRepository.findAll();
	}

	@Override
	public void deleteByObject(TSalesOrderItems persistence) {
		this.salesOrderItemsRepository.delete(persistence);
	}

	@Override
	public void deleteByPrimaryKey(Long id) {
		this.salesOrderItemsRepository.delete(id);
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<TSalesOrderItems> getByProperty(String property, Object value) {
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TSalesOrderItems.class).add(org.hibernate.criterion.Expression.eq(property, value));
		return criteria.list();
	}

	@Transactional
	@Override
	public int updateSalesOrderItems(List<SalesOrderItemsDTO> salesOrderItemsList,TUser currentUser,List<TVendor> vendorList) {
		//
//		List<String> checkList=new ArrayList<String>();
//		if(checkValue!="")
//		{
//			String[] checkArray=checkValue.split(",");
//			checkList=Arrays.asList(checkArray);
//		}
		
		int i = 0;
		if (Collections.isEmpty(salesOrderItemsList))
			return i;
		//Date now = new Date();
		String cUser = CurrentUserUtils.getInstance().getUsername();
		//Long pipelineHeaderId = null;
		for (SalesOrderItemsDTO salesOrderItem : salesOrderItemsList) {
			double oldDelivered=0.0;
			if(salesOrderItem.getOldquantityDelivered()!=null)
			{
				oldDelivered = salesOrderItem.getOldquantityDelivered();
			}

			//选中，并且填写了
			if(salesOrderItem.getQuantityDelivered()!=null)
			{
				//Double subTotal=salesOrderItem.getSubTotal()-salesOrderItem.getQuantityDelivered();
				salesOrderItemsRepository.updateSalesOrderItems(salesOrderItem.getId(), 
						salesOrderItem.getQuantityDelivered()+oldDelivered, 
						new Date(),
						salesOrderItem.getActualTime(), 
						cUser);
				
				purchaseOrderItemsRepository.updatePurchaseOrderItems(salesOrderItem.getId(), 
						salesOrderItem.getQuantityDelivered()+oldDelivered, 
						new Date(),
						salesOrderItem.getActualTime(), 
						cUser);
			}
			++i;
		}
		addSalesOrderExecution(salesOrderItemsList,currentUser,vendorList);
		addPurchaseOrderExecution(salesOrderItemsList,currentUser,vendorList);
		
		addOrderPayment(salesOrderItemsList.get(0).getSalesOrderID());
		
		return i;
	}
	
	private void addOrderPayment(long salesOrderID)
	{
		
	}
	
	/**
	 * save TSalesOrderExecution and TSalesOrderExecutionItems
	 * 
	 * @param salesOrderItems
	 */
	private void addSalesOrderExecution(List<SalesOrderItemsDTO> salesOrderItems,TUser currentUser,List<TVendor> vendorList)
	{
			TSalesOrder salesOrder=new TSalesOrder();
			salesOrder.setId(salesOrderItems.get(0).getSalesOrderID());
			
			//UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
			//TUser currentUser = this.userService.getObject(userDTO.getId());
			//List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
			TVendor vendor = vendorList.get(0);
			
			TSalesOrderExecution orderExecution=new TSalesOrderExecution();
			orderExecution.setDelete(false);//��ɾ��
			orderExecution.setOrderNo(1);
			orderExecution.setOrderExecutionType(false);
			orderExecution.setConfirmTime(new Date());
			orderExecution.setCreatedBy(currentUser.getUsername());
			orderExecution.setUpdatedBy(currentUser.getUsername());
			orderExecution.settVendor(vendor);
			orderExecution.settSalesOrder(salesOrder);
			orderExecution.settUser(currentUser);
			orderExecution.setGmtCreateTime(new Date());
			orderExecution.setGmtUpdateTime(new Date());
			//salesOrderExecutionService.save(orderExecution);
			salesOrderExecutionRepository.save(orderExecution);
			
			for (int i=0;i<salesOrderItems.size();i++) 
			{
				SalesOrderItemsDTO orderItem=salesOrderItems.get(i);
				if(orderItem.getQuantityDelivered()!=null)
				{
					TSalesOrderExecutionItems orderExecutionItems=new TSalesOrderExecutionItems();
					orderExecutionItems.settSalesOrderExecution(orderExecution);
					orderExecutionItems.setOrderNo(i+1);
					orderExecutionItems.setQuantityDelivered(orderItem.getQuantityDelivered());
					orderExecutionItems.setQuantityConfirmed(orderItem.getQuantityConfirmed());
					TMaterialMasterClient masterClient=new TMaterialMasterClient();
					masterClient.setId(orderItem.getMaterialId());
					orderExecutionItems.settMaterialMasterClient(masterClient);
					orderExecutionItems.setGmtCreateTime(new Date());
					orderExecutionItems.setGmtUpdateTime(new Date());
					orderExecutionItems.setCreatedBy(currentUser.getUsername());
					orderExecutionItems.setUpdatedBy(currentUser.getUsername());
					orderExecutionItems.setDelete(false);
					
					//salesOrderExecutionItemService.save(orderExecutionItems);
					salesOrderExecutionItemsRepository.save(orderExecutionItems);
				}
			}				
	}
	
	/**
	 * save TPurchaseOrderExecution and TPurchaseOrderExecutionItems
	 * 
	 * @param salesOrderItems
	 */
	private void addPurchaseOrderExecution(List<SalesOrderItemsDTO> salesOrderItems,TUser currentUser,List<TVendor> vendorList)
	{
		TPurchaseOrder tPurchaseOrder=new TPurchaseOrder();
		tPurchaseOrder.setId(salesOrderItems.get(0).getSalesOrderID());
		
		//UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		//TUser currentUser = this.userService.getObject(userDTO.getId());
		//List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
		TVendor vendor = vendorList.get(0);
		
		TPurchaseOrderExecution orderExecution=new TPurchaseOrderExecution();
		orderExecution.setDelete(false);//��ɾ��
		orderExecution.setOrderNo(1);
		orderExecution.setOrderExecutionType(false);
		orderExecution.setConfirmTime(new Date());
		orderExecution.setCreatedBy(currentUser.getUsername());
		orderExecution.setUpdatedBy(currentUser.getUsername());
		orderExecution.settVendor(vendor);
		orderExecution.settPurchaseOrder(tPurchaseOrder);
		orderExecution.settUser(currentUser);
		orderExecution.setGmtCreateTime(new Date());
		orderExecution.setGmtUpdateTime(new Date());
		//purchaseOrderExecutionService.save(orderExecution);
		purchaseOrderExecutionRepository.save(orderExecution);
		
		for (int i=0;i<salesOrderItems.size();i++) 
		{
			SalesOrderItemsDTO orderItem=salesOrderItems.get(i);
			if(orderItem.getQuantityDelivered()!=null)
			{
				TPurchaseOrderExecutionItems orderExecutionItems=new TPurchaseOrderExecutionItems();
				orderExecutionItems.settPurchaseOrderExecution(orderExecution);
				orderExecutionItems.setOrderNo(i+1);
				orderExecutionItems.setQuantityDelivered(orderItem.getQuantityDelivered());
				orderExecutionItems.setQuantityConfirmed(orderItem.getQuantityConfirmed());
				TMaterialMasterClient masterClient=new TMaterialMasterClient();
				masterClient.setId(orderItem.getMaterialId());
				orderExecutionItems.settMaterialMasterClient(masterClient);
				orderExecutionItems.setGmtCreateTime(new Date());
				orderExecutionItems.setGmtUpdateTime(new Date());
				orderExecutionItems.setCreatedBy(currentUser.getUsername());
				orderExecutionItems.setUpdatedBy(currentUser.getUsername());
				orderExecutionItems.setDelete(false);
				
				//purchaseOrderExecutionItemService.save(orderExecutionItems);
				purchaseOrderExecutionItemsRepository.save(orderExecutionItems);
			}
		}		
	}
}
